--
--  Copyright 2022 The Open Islands Authors. All Rights Reserved.
--
--  Licensed under the Apache License, Version 2.0 (the "License");
--  you may not use this file except in compliance with the License.
--  You may obtain a copy of the License at
--
--      http://www.apache.org/licenses/LICENSE-2.0
--
--  Unless required by applicable law or agreed to in writing, software
--  distributed under the License is distributed on an "AS IS" BASIS,
--  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
--  See the License for the specific language governing permissions and
--  limitations under the License.
--
local _M = {
    _VERSION = '0.1'
}

local yaml_parser = require("tinyyaml")
local utils = require "utils"
local log = require("log")
local constant = require("constant")

local ngx = ngx
local new_timer = ngx.timer.at

function _M.load_config()
    local config_path = ngx.config.prefix().."../../conf/oi.yaml"
    log.info("load config from", config_path)
    local content, err = utils.read_file_data(config_path)
    if content == nil then
        log.error("config file no data")
        return
    end
    local oi_conf = yaml_parser.parse(content)
    if oi_conf["federatedproxy"] == nil or oi_conf["master"] == nil or oi_conf["worker"] == nil then
        log.error("can not found federatedproxy or master or worker config")
    end
    log.info("load config:")

    _M["node_id"] = oi_conf["node"]["node_id"]
    _M[constant.APISERVER] = oi_conf[constant.APISERVER]
    _M[constant.MASTER] = oi_conf[constant.MASTER]
    _M[constant.WORKER] = oi_conf[constant.WORKER]
    _M[constant.FEDERATEDPROXY] = oi_conf[constant.FEDERATEDPROXY]
    _M["default_engines"] = oi_conf["default_engines"]
    _M["kafka"] = oi_conf["kafka"]

    _M.print_config("node_id", _M["node_id"])
    _M.print_config("apiserver", _M["apiserver"])
    _M.print_config("master", _M["master"])
    _M.print_config("worker", _M["worker"])
    _M.print_config("federatedproxy", _M["federatedproxy"])
    _M.print_config("default_engines", _M["default_engines"])
    _M.print_config("kafka", _M["kafka"])
    log.info("load config finish")
end

function _M.print_config(name, content)
    if type(content) == "table" then
        for k, v in pairs(content) do
            _M.print_config(name.."."..k, v)
        end
    else
        log.info(name, ": ", content)
    end
end

function _M.crontab_reload()
    _M.load_config()
    local ok, err = new_timer(60, _M.crontab_reload)
    if not ok then
        if err ~= "process exiting" then
            log.error("failed to create timer: ")
        end
        _M.load_config()
        return
    end
end

return _M

